package model

/*
@Project        :   update_tools
@FileName       :   main.go
@Author         :   Administrator
@Datetime       :   2020/9/11 0:41
@Software       :   GoLand
@Show           :
*/

import (
	"encoding/xml"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"io/ioutil"
	"os"
	"time"
)

type Conf struct {
	DBIP       string `xml:"DBIP"`
	DBPort     int    `xml:"DBPort"`
	DBPassWord string `xml:"DBPassWord"`
	DBUserName string `xml:"DBUserName"`
	DBName     string `xml:"DBName"`
}

type UpdateFile struct {
	Id          int    `gorm:"AUTO_INCREMENT,primary_key"`
	FileName    string `gorm:"size:255"`
	Url         string `gorm:"size:500"`
	FileMd5     string `gorm:"size:32"`
	Lastver     string `gorm:"size:20"`
	Size        int64
	NeedRestart string `gorm:"size:5"`
	Zipped      string `gorm:"size:5"`
	ModName     string `gorm:"size:20"`
	CreateTime  time.Time
}

func DbInit() *gorm.DB {
	DBConfig := InitConfig()
	Mysql_Conn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&loc=Local&parseTime=true",
		DBConfig.DBUserName, DBConfig.DBPassWord, DBConfig.DBIP, DBConfig.DBPort, DBConfig.DBName)
	var db, err = gorm.Open("mysql", Mysql_Conn)
	if err != nil {
		fmt.Println(err)
	}
	db.CreateTable(&UpdateFile{})
	return db
}

func InitConfig() Conf {
	file, _ := os.Open("conf.xml") // For read access.
	data, _ := ioutil.ReadAll(file)

	v := Conf{}
	_ = xml.Unmarshal(data, &v)
	return v
}
